package com.jiaai.util.logaop;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.jiaai.system.api.ILogApi;
import com.jiaai.system.model.LogVO;
import com.jiaai.util.HttpClientUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * class_name:LogAspect
 * describe:------------------>日志切面
 * create_user:张昉平
 * create_date:2018/1/15
 * create_time:10:53
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Reference
    private ILogApi iLogApi;

    @Before(value = "@annotation(logAnno)")
    public void beforeAndLog(JoinPoint joinPoint, LogAnno logAnno){
        String nickName = (String) request.getAttribute("userName");
        String ipAddr = HttpClientUtil.getIpAddress(request);

        String methodName = logAnno.methodName();
        Integer methodType = logAnno.methodType();

        LogVO vo = new LogVO();

        vo.setIpAddr(ipAddr);
        vo.setMethodName(methodName);
        vo.setMethodType(methodType);
        if (nickName == null){
            vo.setDetail((String) joinPoint.getArgs()[0]);
            vo.setUserName((String) joinPoint.getArgs()[0]);
        }else {
            vo.setUserName(nickName);
            vo.setDetail(JSONObject.toJSONString(joinPoint.getArgs()));
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    iLogApi.add(vo);
                }catch (Exception e){
                }
            }
        }).start();
    }
}
